﻿using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using System;
using System.Runtime.InteropServices;

namespace MapFormsApp.Helpers
{
    /// <summary>
    /// 几何操作工具类（静态方法集合）
    /// </summary>
    public static class GeometryHelper
    {
        #region 几何创建
        /// <summary>
        /// 创建点几何
        /// </summary>
        public static IPoint CreatePoint(double x, double y, ISpatialReference spatialRef = null)
        {
            IPoint point = new PointClass();
            point.X = x;
            point.Y = y;
            point.SpatialReference = spatialRef;
            return point;
        }

        /// <summary>
        /// 从WKT字符串创建几何（支持点/线/面）
        /// </summary>
        //public static IGeometry GeometryFromWkt(string wkt, ISpatialReference spatialRef = null)
        //{
        //    if (string.IsNullOrEmpty(wkt)) return null;

        //    try
        //    {
        //        // 使用 IWkt 接口解析 WKT
        //        IWKSParser wktParser = new WKSParserClass();
        //        IGeometry geometry;
        //        wktConverter.ReadFromWkt(wkt, out geometry, out _);

        //        if (spatialRef != null)
        //            geometry.SpatialReference = spatialRef;

        //        return geometry;
        //    }
        //    catch (COMException ex)
        //    {
        //        throw new ArgumentException("WKT 解析失败", ex);
        //    }
        //}
        #endregion

        #region 几何分析
        /// <summary>
        /// 计算两个几何间的欧氏距离（单位与空间参考一致）
        /// </summary>
        public static double CalculateDistance(IGeometry geom1, IGeometry geom2)
        {
            if (geom1 == null || geom2 == null) return -1;
            IProximityOperator proximity = geom1 as IProximityOperator;
            return proximity?.ReturnDistance(geom2) ?? -1;
        }

        /// <summary>
        /// 检查几何有效性（拓扑验证）
        /// </summary>
        public static bool IsGeometryValid(IGeometry geometry)
        {
            if (geometry == null) return false;
            ITopologicalOperator topo = geometry as ITopologicalOperator;
            try
            {
                topo?.Simplify();
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 几何转换
        /// <summary>
        /// 投影坐标系转换
        /// </summary>
        public static IGeometry ProjectGeometry(IGeometry geometry, ISpatialReference targetSpatialRef)
        {
            if (geometry == null) return null;

            IClone cloneable = geometry as IClone;
            if (cloneable == null) return null;

            IGeometry clonedGeometry = cloneable.Clone() as IGeometry;
            clonedGeometry.Project(targetSpatialRef);
            return clonedGeometry;
        }

        /// <summary>
        /// 将几何转换为JSON格式（Esri Geometry规范）
        /// </summary>
        //public static string ToJsonGeometry(IGeometry geometry)
        //{
        //    if (geometry == null) return string.Empty;

        //    IJSONWriter jsonWriter = new JSONWriterClass();
        //    IGeoJsonConverter geoJsonConverter = new GeoJsonConverterClass();
        //    geoJsonConverter.WriteGeometry(geometry, jsonWriter, null);
        //    return jsonWriter.GetString();
        //}
        #endregion

        #region 几何操作
        /// <summary>
        /// 合并多个几何图形（Union操作）
        /// </summary>
        public static IGeometry UnionGeometries(params IGeometry[] geometries)
        {
            if (geometries == null || geometries.Length == 0) return null;

            ITopologicalOperator unionResult = geometries[0] as ITopologicalOperator;
            for (int i = 1; i < geometries.Length; i++)
            {
                unionResult = unionResult?.Union(geometries[i]) as ITopologicalOperator;
            }
            return unionResult as IGeometry;
        }

        /// <summary>
        /// 创建缓冲区（自动处理单位转换）
        /// </summary>
        public static IGeometry CreateBuffer(IGeometry geometry, double distance, esriUnits units = esriUnits.esriMeters)
        {
            if (geometry == null) return null;

            // 确保几何为投影坐标系
            if (geometry.SpatialReference is IGeographicCoordinateSystem)
            {
                throw new ArgumentException("地理坐标系需先转换为投影坐标系");
            }

            ITopologicalOperator topoOperator = geometry as ITopologicalOperator;
            //IBuffer2 buffer = new BufferClass();
            //buffer.BufferDistance = distance;
            //buffer.Unit = units;
            //return topoOperator?.Buffer(buffer);
            return null;
        }
        #endregion

        #region 几何工具
        /// <summary>
        /// 计算多边形面积（自动转换单位）
        /// </summary>
        public static double CalculateArea(IPolygon polygon, esriAreaUnits targetUnit = esriAreaUnits.esriSquareMeters)
        {
            if (polygon == null) return 0;

            IArea area = polygon as IArea;
            //if (area?.SpatialReference == null) return area?.Area ?? 0;

            //IUnitConverter unitConverter = new UnitConverterClass();
            //return unitConverter.ConvertArea(
            //    area.Area,
            //    (esriUnits)area.SpatialReference.FactoryCode,
            //    targetUnit
            //);
            return 0;
        }

        /// <summary>
        /// 简化几何图形（拓扑校正）
        /// </summary>
        public static IGeometry SimplifyGeometry(IGeometry geometry)
        {
            if (geometry == null) return null;

            ITopologicalOperator topo = geometry as ITopologicalOperator;
            topo?.Simplify();
            return geometry;
        }
        #endregion

        #region COM对象管理
        /// <summary>
        /// 安全释放几何对象（处理COM资源）
        /// </summary>
        public static void ReleaseGeometry(IGeometry geometry)
        {
            if (geometry != null && Marshal.IsComObject(geometry))
            {
                Marshal.ReleaseComObject(geometry);
            }
        }
        #endregion
    }
}